﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinApp.i18n;
using WinApp.Model;
using WinApp.Model.AjaxResult;
using WinApp.Until;
using WinApp.ViewModel;

namespace WinApp.View
{
    public partial class CourseList : UserControl
    {
        public WinApp _parent { get; set; }

        public int _pageIndex { get; set; } = 0;
        public int _currentListCount { get; set; } = 0;

        public UILabel _lbMore;
        public UILabel _lbNotData;
        public int _lastRowY { get; set; } = 0;
        private List<MyCourseSessionEntityOutputDto> _mainRows = new List<MyCourseSessionEntityOutputDto>();

        public SearchMyCourseSessionEntity _searchMyCourseSessionEntity = new SearchMyCourseSessionEntity
        {
            StandardCourseType = 2,
            LearningStatuStr = 2,
            PageCondition = new Model.PageCondition()
            {
                PageIndex = 1,
                PageSize = 10,
                SortConditions = new List<Model.SortCondition> { new Model.SortCondition() { SortField = "BeginTime", ListSortDirection = Model.ListSortDirection.Ascending } }
            }
        };

        public CourseList()
        {
            InitializeComponent();
            pictureBox1.Image = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/plane.png");
            this.AutoScroll = true;
            this.panel1.AutoScroll = true;
            this.panel1.MouseWheel += panell_MouseWheel;
            uiGroupBox1.Click += Gbox_Click;
            //LoadPanellData();

            this.lbSyncCbtRecord.Text = Language.GetLang("syncCbt");

        }

        private void panell_MouseWheel(object? sender, MouseEventArgs e)
        {
            var vScrollPosition = panel1.VerticalScroll.Value;
            if (vScrollPosition == panel1.VerticalScroll.Maximum - panel1.VerticalScroll.LargeChange + 1)
            {
                //MessageBox.Show("已经滚动到底部");
                return;
            }
        }

        public void LoadPanellData()
        {
            //_parent._ShowProcessForm();
            LoadingHelper.ShowLoadingScreen();//显示
            this.panel1.Controls.Clear();
            _lastRowY = 0;
            _currentListCount = 0;
            _lbMore = new UILabel();
            _lbMore.Text = "More";
            _lbMore.ForeColor = Color.Blue;
            _lbMore.Cursor = Cursors.Hand;
            _lbMore.TextAlign = ContentAlignment.MiddleCenter;
            _lbMore.Location = new Point(0, 0);
            _lbMore.Click += _lbMore_Click;
            _lbMore.Visible = false;
            this.panel1.Controls.Add(_lbMore);

            _lbNotData = new UILabel();
            _lbNotData.Text = "No more data available";
            _lbNotData.Cursor = Cursors.Hand;
            _lbNotData.TextAlign = ContentAlignment.MiddleCenter;
            _lbNotData.Location = new Point(0, 0);
            _lbNotData.Width = 200;
            _lbNotData.Visible = false;
            this.panel1.Controls.Add(_lbNotData);

            _searchMyCourseSessionEntity.PageCondition.PageIndex = 1;
            _mainRows = new List<MyCourseSessionEntityOutputDto>();
            QueryData();

            //_parent._HideProcessForm();
            LoadingHelper.CloseForm();//关闭

        }


        public void QueryData()
        {


            // 进行耗时操作，例如加载接口
            //var result = WebApiHelper.PostWebAPI<PageDataRow>("api/Admin/Enrollment/ReadByMyEnrollment", _searchMyCourseSessionEntity);
            var result = CourseListModel.ReadByMyEnrollment(_searchMyCourseSessionEntity);
            if (result == null || result.Total <= 0)
            {
                _lbMore.Visible = false;
                _lbNotData.Visible = true;
                _lbNotData.Location = new Point(450, 20 + 30);
                return;
            }
            List<MyCourseSessionEntityOutputDto> DataRows = JsonConvert.DeserializeObject<List<MyCourseSessionEntityOutputDto>>(result.Rows.ToString());
            if (DataRows == null || DataRows.Count <= 0)
            {
                _lbMore.Visible = false;
                _lbNotData.Visible = true;
                _lbNotData.Location = new Point(450, 20 + 30);
                return;
            }
            //this.panel1.Controls.Clear();
            //foreach (var item in _mainRows)
            //{
            //    //_currentListCount = 10;
            //    UIGroupBox gbox = new UIGroupBox();
            //    gbox.Width = 1035;
            //    gbox.Height = 140;
            //    gbox.Text = (_currentListCount + 1).ToString();
            //    gbox.Tag = item.CourseSessionId.ToString();
            //    gbox.Location = new Point(3, _currentListCount * 140);
            //    gbox.Click += Gbox_Click;
            //    this.panel1.Controls.Add(gbox);
            //    FillInPanell(gbox, item);
            //    _currentListCount++;
            //}
            for (int i = 0; i < DataRows.Count; i++)
            {



                UIGroupBox gbox = new UIGroupBox();
                gbox.Width = 1035;
                gbox.Height = 140;
                gbox.Text = (_currentListCount + 1).ToString();
                //gbox.Tag = DataRows[i].Id.ToString();

                TagCourseSessionDto tagCourseSessionDto = new TagCourseSessionDto()
                {
                    CourseId = DataRows[i].CourseId,
                    CourseSessionId = DataRows[i].CourseSessionId,
                    CourseEnrollmentId = DataRows[i].Id,
                    StrStartTime = DataRows[i].BeginTime.HasValue ? DataRows[i].BeginTime.Value.ToString("yyyy.MM.dd") : "None",
                    StrEndTime = DataRows[i].EndTime.HasValue ? DataRows[i].EndTime.Value.ToString("yyyy.MM.dd") : "None",
                };
                gbox.Tag = tagCourseSessionDto;


                if (_lastRowY != 0)
                {
                    gbox.Location = new Point(3, _lastRowY - panel1.VerticalScroll.Value + 140 + 30);
                }
                else
                {
                    //30预留的是同步按钮的高度，140是group的高度；
                    gbox.Location = new Point(3, i * 140 + 30);
                }
                _lastRowY = _currentListCount * 140;
                gbox.Click += Gbox_Click;

                this.panel1.Controls.Add(gbox);
                FillInPanell(gbox, DataRows[i]);

                _currentListCount++;
            }

            if (_currentListCount < result.Total)
            {
                //if (_lastRowY != 0)
                //{
                //    gbox.Location = new Point(3, _lastRowY - panel1.VerticalScroll.Value + 140);
                //}
                //else
                //{
                //    gbox.Location = new Point(3, i * 140);
                //}
                _lbMore.Visible = true;
                _lbMore.Location = new Point(450, _lastRowY - panel1.VerticalScroll.Value + 140 + 30);
                //_lbMore.Location = new Point(450, _lastRowY + 140);
            }
            else
            {

                _lbMore.Visible = false;
                _lbNotData.Visible = true;
                _lbNotData.Location = new Point(450, _lastRowY - panel1.VerticalScroll.Value + 140 + 30);
            }
        }

        private void _lbMore_Click(object? sender, EventArgs e)
        {
            _searchMyCourseSessionEntity.PageCondition.PageIndex = _searchMyCourseSessionEntity.PageCondition.PageIndex + 1;
            QueryData();
        }

        public void FillInPanell(UIGroupBox gb, MyCourseSessionEntityOutputDto item)
        {
            var defaultCbtCover = FileHelper.loadImageFromLocalPath(@"FileFolder/Icon/book.png");
            if (!string.IsNullOrEmpty(item.SurfacePlot))
            {
                defaultCbtCover = FileHelper.LoadImageFromWebUriAsync(GlobalVariables.WebIp + "fileFolder/courseSurfaces/" + WebApiHelper._Tenancy + "/" + item.SurfacePlot);
            }

            PictureBox pictureBox = new PictureBox();
            pictureBox.Width = 107;
            pictureBox.Height = 107;
            pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBox.Location = new Point(26, 18);
            pictureBox.Image = defaultCbtCover;
            gb.Controls.Add(pictureBox);

            UIAvatar uIAvatar = new UIAvatar();
            uIAvatar.AvatarSize = 35;
            uIAvatar.Width = 42;
            uIAvatar.Height = 37;
            uIAvatar.Shape = UIShape.Circle;
            uIAvatar.Symbol = 61465;
            uIAvatar.FillColor = Color.Transparent;
            uIAvatar.Location = new Point(935, 60);
            gb.Controls.Add(uIAvatar);

            UILabel lbTitle = new UILabel();
            lbTitle.Location = new Point(150, 18);
            lbTitle.Width = 500;
            lbTitle.Text = item.CourseSessionName;
            lbTitle.Font = new Font(lbTitle.Font.Name, lbTitle.Font.Size, FontStyle.Bold);
            gb.Controls.Add(lbTitle);

            UILabel lbCourseUnit = new UILabel();
            lbCourseUnit.Location = new Point(150, 49);
            lbCourseUnit.Width = 200;
            string CourseUnitStr = Language.GetLang("courseUnit") + item.LessonCount;
            lbCourseUnit.Text = CourseUnitStr;
            gb.Controls.Add(lbCourseUnit);

            UILabel lbStatus = new UILabel();
            lbStatus.Location = new Point(150, 72);
            lbStatus.Width = 200;
            var statusStr = string.Empty;
            switch (item.LearningStatu)
            {
                case 1:
                    statusStr = Language.GetLang("incomplete");
                    lbStatus.ForeColor = Color.Orange;
                    break;
                case 2:
                    statusStr = Language.GetLang("completed");
                    lbStatus.ForeColor = Color.Green;
                    break;
                default:
                    statusStr = Language.GetLang("notStarted");
                    break;
            }
            // statusStr;
            lbStatus.Text = UtilHelper.GetLearningStatusStr(item.LearningStatu);
            lbStatus.Font = new Font(lbTitle.Font.Name, lbTitle.Font.Size, FontStyle.Bold);
            gb.Controls.Add(lbStatus);

            UILabel lbTime = new UILabel();
            lbTime.Location = new Point(150, 103);
            lbTime.Width = 500;
            var timeStr = string.Empty;
            var beginTime = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(item.BeginTime), TimeZoneInfo.Local);
            timeStr = Language.GetLang("startTime") + beginTime.ToString("yyyy-MM-dd HH:mm:ss");
            if (item.EndTime != null)
            {
                var endTime = TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(item.EndTime), TimeZoneInfo.Local);
                timeStr += " - " + Language.GetLang("endTime") + beginTime.ToString("yyyy-MM-dd HH:mm:ss");
            }
            lbTime.Text = timeStr;
            gb.Controls.Add(lbTime);

            UILabel lbLearned = new UILabel();
            lbLearned.Location = new Point(880, 100);
            lbLearned.Width = 200;
            //lbLearned.TextAlign = ContentAlignment.MiddleCenter;
            lbLearned.ForeColor = Color.Red;
            var learnedStr = string.Empty;
            if (item.CumulativeLearningTime != null && item.CumulativeLearningTime > 0)
            {
                learnedStr = Language.GetLang("learned") + UtilHelper.DoubleTimeToString(item.CumulativeLearningTime);
            }
            lbLearned.Text = learnedStr;

            gb.Controls.Add(lbLearned);
        }

        private void Gbox_Click(object? sender, EventArgs e)
        {

            UIGroupBox clickGroupBox = sender as UIGroupBox;
            if (clickGroupBox == null)
                return;

            var tagCourseSessionDto = clickGroupBox.Tag as TagCourseSessionDto;
            if (tagCourseSessionDto == null)
            {
                UIMessageDialog.ShowMessageDialog(Language.GetLang("notFindTag"), UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                return;
            }

            AjaxResult result = CourseListModel.CheckOpenCourseDetails(tagCourseSessionDto);
            if (result.Type != AjaxResultType.Success)
            {
                string strCheckMsg = string.Empty;
                if (result.Content == "1103")
                {
                    strCheckMsg = Language.GetLang("page_dataValidError");
                }
                else if (result.Content == "1135" || result.Content == "ConditionNotComplete")
                {
                    strCheckMsg = Language.GetLang("page_examConditionIsNotComplete");
                }
                else
                {
                    strCheckMsg = Language.GetLang("page_examConditionIsNotComplete");
                }

                UIMessageDialog.ShowMessageDialog(strCheckMsg, UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false);
                return;
            }

            //通知服务器开始学习
            CourseListModel.LanuchCourseSession(tagCourseSessionDto);


            _parent.SetNavMenulPageIndex(NavPageIndex.courseDetails, clickGroupBox.Tag);
        }

        private void lbSyncCbtRecord_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            UIMessageDialog.ShowMessageDialog("Ok", UILocalize.SuccessTitle, showCancelButton: false, UIStyle.Green, false);
        }
    }
}
